package com.bocai.yuweiwangluo.presenter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import com.bocai.yuweiwangluo.activity.SetNewPsdSuccessActivity;
import com.bocai.yuweiwangluo.base.BaseView;
import com.bocai.yuweiwangluo.bean.BaseBean;
import com.bocai.yuweiwangluo.net.MyOkHttpClient;
import com.bocai.yuweiwangluo.utils.SharePrefencesUtil;
import com.bocai.yuweiwangluo.utils.UrlData;
import com.bocai.yuweiwangluo.viewModel.IBindingPhoneView;
import com.google.gson.Gson;


/**
 * Created by admin on 2015/12/16.
 */
public class BindingPhonePresenter {
    private IBindingPhoneView iBindingPhoneView;
    private static final int RESPONSE_SUCCEED = 1;
    private static final int RESPONSE_FAILED = 2;
    private Context context;
    private BaseBean bean;
    private int requsttype;
    private int delaytime;
    private Button getCodebtn;
    private BaseView baseView;
    private MyOkHttpClient myOkHttpClient;
    private int code;
    public BindingPhonePresenter(Context context, IBindingPhoneView iBindingPhoneView, Button getCodebtn, BaseView baseView)
    {
        myOkHttpClient = new MyOkHttpClient(context,baseView);
        this.context = context;
        this.iBindingPhoneView = iBindingPhoneView;
        this.getCodebtn=getCodebtn;
        this.baseView=baseView;
    }

    /**
     * 验证码验证
     */
    public void verificationCode()
    {
        baseView.showLoading();
        requsttype=2;

        if("".equals(iBindingPhoneView.getTel()))
        {
            Toast.makeText(context,"请输入手机号",Toast.LENGTH_SHORT).show();
        }
        else if (iBindingPhoneView.getTel().length()!= 11)
        {
            Toast.makeText(context, "手机号错误", Toast.LENGTH_SHORT).show();
        }
        else if ("".equals(iBindingPhoneView.getCode()))
        {
            Toast.makeText(context, "请输入验证码", Toast.LENGTH_SHORT).show();
        } else
        {
            myOkHttpClient.verificationCode(UrlData.BASEURL + UrlData.VERIFICATIONCODE, iBindingPhoneView.getTel(), iBindingPhoneView.getCode(),handler);
        }
    }

//    /**
//     * 手机端随机生成4位验证码，发送给服务器，服务器将其保存在数据库中
//     */
//    public void saveCode()
//    {
//        code= (int) (Math.random()*9000+1000);//随机生成4位验证码
//        Log.e("code",code+"");
//        if ("".equals(iBindingPhoneView.getTel()))
//        {
//            Toast.makeText(context,"请输入手机号",Toast.LENGTH_SHORT).show();
//        }
//        if (iBindingPhoneView.getTel().length() != 11)
//        {
//            Toast.makeText(context, "手机号错误", Toast.LENGTH_SHORT).show();
//        } else
//        {
//            requsttype = 1;
//            myOkHttpClient.saveCode(UrlData.BASEURL+UrlData.SAVECODE, iBindingPhoneView.getTel(),String.valueOf(code), handler);
//        }
//    }
    /**
     *获取验证码
     */
    public void getCode()
    {
        if ("".equals(iBindingPhoneView.getTel()))
        {
            Toast.makeText(context,"请输入手机号",Toast.LENGTH_SHORT).show();
        }
        if (iBindingPhoneView.getTel().length() != 11)
        {
            Toast.makeText(context, "手机号错误", Toast.LENGTH_SHORT).show();
        } else
        {
            requsttype = 1;
            myOkHttpClient.getCode(UrlData.BASEURL + UrlData.GETCODE, iBindingPhoneView.getTel(), handler);
        }
    }
    /**
     * 绑定请求请求
     */
    public void binding(){
        requsttype = 3;
        myOkHttpClient.updataPhone(UrlData.BASEURL + UrlData.UPDATAPHONE, SharePrefencesUtil.getUser_id(context),iBindingPhoneView.getTel(), handler);
    }

    /**
     * 将随机生成的验证码通过短信的形式发送到用户的手机上
     * @param code
     */
    private void sendMsm(String code)
    {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(iBindingPhoneView.getTel(),null,code, null, null);
    }

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            String result = (String) msg.obj;
            Gson gson = new Gson();
            switch (msg.what)
            {
                case RESPONSE_SUCCEED:
                    Log.e("tag",result);
                    bean = gson.fromJson(result, BaseBean.class);
                    if (requsttype == 1)//发送验证码
                    {
                        if (0==bean.getState())
                        {
                            try
                            {
                                Toast.makeText(context,"验证码已发送至手机",Toast.LENGTH_SHORT).show();
                                delaytime = 60;
                                getCodebtn.setClickable(false);
                                new Thread(new ThreadShow()).start();

                            } catch (Exception e)
                            {
                            }
                        } else
                        {
                            Toast.makeText(context, bean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }else if(requsttype == 2)//验证验证码
                    {
                        if (0==bean.getState())
                        {
                            binding();
                        } else
                        {
                            baseView.hideLoading();
                            Toast.makeText(context, bean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    } else if (requsttype == 3)
                    {//修改绑定手机号
                        baseView.hideLoading();
                        if (0==bean.getState())
                        {
                            SharedPreferences sharedPreferences=context.getSharedPreferences("user",Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor=sharedPreferences.edit();
                            editor.putString("user_name",iBindingPhoneView.getTel());
                            editor.commit();
                            Intent intent=new Intent(context,SetNewPsdSuccessActivity.class);
                            context.startActivity(intent);
                            iBindingPhoneView.finishActivity();//绑定成功 退出该界面
                            Toast.makeText(context,"绑定成功", Toast.LENGTH_SHORT).show();
                        } else
                        {
                            Toast.makeText(context, bean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case RESPONSE_FAILED:
                    baseView.hideLoading();
                    baseView.showError(result);
                    break;
                case 88:
                    getCodebtn.setText(delaytime + "s");
                    if (delaytime == 0)
                    {
                        getCodebtn.setClickable(true);
                        getCodebtn.setText("再次获取");
                    }
                    break;
            }
        }
    };
    // 线程类
    class ThreadShow implements Runnable
    {
        @Override
        public void run()
        {
            while (delaytime > 0)
            {
                try
                {
                    Thread.sleep(1000);
                    delaytime--;
                    Message msg = new Message();
                    msg.what = 88;
                    handler.sendMessage(msg);
                } catch (Exception e)
                {
                }
            }
        }
    }
}